<?php
/**
 *
 * @author: xaboy<365615158@qq.com>
 * @day: 2017/11/13
 */

namespace app\base\model\system;

use app\base\model\ModelTrait;
use think\Model;

/**
 * 身份管理 model
 * Class SystemRole
 * @package app\base\model\system
 */
class SystemRole extends Model
{
    use ModelTrait;

    protected $table = 'xy_system.xy_system_role';

    public static function setRulesAttr($value)
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    /**
     * 选择管理员身份
     * @param int $level
     * @param string $field
     * @return array
     */
    public static function getRole($level = 0, $field = 'role_id,role_name')
    {
        return self::where('status', 1)->where('level', '=', $level)->column($field);
    }


    public static function rolesByAuth($rules)
    {
        if (empty($rules)) {
            return [];
        }
        $rules = self::where('role_id', 'IN', $rules)->where('status', '1')->column('menu_ids');
        $rules = array_unique(explode(',', implode(',', $rules)));
        $_auth = SystemMenus::all(function ($query) use ($rules) {
            $query->where('menu_id', 'IN', $rules)
                ->where('controller|action', '<>', '')
                ->field('module,controller,action,params');
        });
        return self::tidyAuth($_auth ?: []);
    }

    public static function getAllAuth()
    {
        static $auth = null;
        $auth === null && ($auth = self::tidyAuth(SystemMenus::all(function ($query) {
            $query->where('controller|action', '<>', '')->field('module,controller,action,params');
        }) ?: []));
        return $auth;
    }

    protected static function tidyAuth($_auth)
    {
        $auth = [];
        foreach ($_auth as $k => $val) {
            $auth[] = SystemMenus::getAuthName($val['action'], $val['controller'], $val['module'], $val['params']);
        }
        return $auth;
    }


    public static function getRoleList($where)
    {
        $model = new self;
        if ($where['role_name']) {
            $model = $model->where('role_name', 'LIKE', (string)$where['role_name']);
        }
        if ($where['status']) {
            $model = $model->where('status', $where['status']);
        }
        $model->where('level', '=', bcadd($where['level'], 1, 0));
        $items = $model->select();

        if ($items) {
            foreach ($items as &$item) {
                $item['rule_list'] = SystemMenus::where('menu_id', 'IN',
                    array_unique(explode(',', $item['menu_ids'])))->where('level', 1)->column('menu_name');
            }
        }

        return $items;
    }

}